import { merge } from 'lodash-es'
import Vue from 'vue'

import {
  GetPhoneNumberResult,
  getWxMiniUserPhoneApi,
  getWxNewPhoneNoInfoApi
} from '@/api/sys/paas'
import { useGlobalSetting } from '@/settings/system'

export declare interface GetPhoneNumberEvent {
  detail: {
    code?: string
    iv?: string
    encryptedData?: string
  }
}

export const useGetPhoneNumber = (
  callback?: (result: GetPhoneNumberResult, err?: unknown) => unknown
) => {
  const payload = Vue.observable({
    loading: false,
    canInput: false,
    phone: ''
  })

  // 兼容旧版接口，后续可以移除
  // uni.checkSession({
  //   fail: () => userStore.Login()
  // })

  const { wxAppId } = useGlobalSetting()

  const bindFn = async (ev: GetPhoneNumberEvent) => {
    payload.loading = true
    payload.canInput = false
    try {
      if (ev.detail.code) {
        const result = await getWxNewPhoneNoInfoApi({
          code: ev.detail.code,
          miniAppId: wxAppId
        })
        payload.phone = result.phoneNumber
        callback?.call(this, result)
        if (result.phoneNumber) return
      }

      if (ev.detail.iv && ev.detail.encryptedData) {
        const result = await getWxMiniUserPhoneApi({
          iv: ev.detail.iv,
          encryptedData: ev.detail.encryptedData,
          wxAppId
        })
        payload.phone = result.phoneNumber
        callback?.call(this, result)
        if (result.phoneNumber) return
      }
    } catch (e) {
      payload.canInput = true
      callback?.call(this, {} as GetPhoneNumberResult, e)
      throw e
    } finally {
      payload.loading = false
    }
  }
  return merge(bindFn, { payload })
}
